package com.elastic.service;

import com.alibaba.fastjson.JSONObject;

import com.elastic.dao.GeoSearchDao;
import com.elastic.domain.GeoSearch;
import org.elasticsearch.common.geo.GeoPoint;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@Service
public class GeoSearchService {

    @Resource
    private GeoSearchDao geoSearchDao;

    public JSONObject geoSearch(GeoSearch search) throws Exception{
        JSONObject out = new JSONObject();
        String type = search.getType();
        List result = new ArrayList<>();

        //type为空则返回所有数据
        if ((type == null) || (type == "")) {
            List list = geoSearchDao.getAll();
            out.put("msg", "succeed");
            out.put("data", list);
            return out;
        }

        //根据type判断采用何种查询
        else if (type.equals("Polygon") || type == "Polygon") {
            List<GeoPoint> list = search.getPoints();
            result = geoSearchDao.searchGeoPolygon(list);
        }

        else if (type.equals("Circle") || type == "Circle") {
            String distance = search.getRadius();
            GeoPoint point = search.getOrigin();
            result = geoSearchDao.searchGeoDistance(distance, point);
        }

        else if (type.equals("Bounding") ||type == "Bounding") {
            if (search.getPoints().size() >= 2) {
                GeoPoint point1 = search.getPoints().get(0);
                GeoPoint point2 = search.getPoints().get(1);
                result = geoSearchDao.searchGeoBoundingBox(point1, point2);
            } else {
                out.put("msg", "failed");
                out.put("data", "Points error");
                return out;
            }
        } else {
            out.put("msg", "failed");
            out.put("data", "Type error");
            return out;
        }
        out.put("msg", "succeed");
        out.put("data", result);
        return out;
    }

}